package com.example.websocketserver.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 创建处理类管理连接和消息
 */
@Component
@ServerEndpoint("/websocket")
public class WebSocketServer {
    private static final ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();
    // 创建定时器每秒发送消息
    private final Timer timer = new Timer();

    @OnOpen
    public void onOpen(Session session) {
        sessionMap.put(session.getId(), session);
        System.out.println("新连接：" + session.getId());

        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                // 构建要广播的消息
                String responseMessage1 = "{\n" +
                        "  \"jsonrpc\": \"2.0\",\n" +
                        "  \"method\": \"notify_status_update\",\n" +
                        "  \"params\": [\n" +
                        "    {\n" +
                        "      \"extruder\": {\n" +
                        "        \"temperature\": 221.6\n" +
                        "      },\n" +
                        "      \"extruder1\": {\n" +
                        "        \"temperature\": 35.21\n" +
                        "      },\n" +
                        "      \"heater_bed\": {\n" +
                        "        \"temperature\": 45.07,\n" +
                        "        \"power\": 0.18676018616526924\n" +
                        "      }\n" +
                        "    },\n" +
                        "    167162.284665092\n" +
                        "  ]\n" +
                        "}";
                String responseMessage2 = "{\n" +
                        "    \"jsonrpc\": \"2.0\",\n" +
                        "    \"method\": \"notify_history_changed\",\n" +
                        "    \"params\": [\n" +
                        "      {\n" +
                        "        \"action\": \"added\",\n" +
                        "        \"job\": {\n" +
                        "          \"end_time\": null,\n" +
                        "          \"filament_used\": 0,\n" +
                        "          \"filename\": \"冰沙机15-7H-180g.gcode\",\n" +
                        "          \"metadata\": {\n" +
                        "            \"size\": 36792344,\n" +
                        "            \"modified\": 1741756827.2894504,\n" +
                        "            \"uuid\": \"8b8c8e08-4cdf-4a82-b673-54818619e882\",\n" +
                        "            \"slicer\": \"OrcaSlicer\",\n" +
                        "            \"slicer_version\": \"2.2.0\",\n" +
                        "            \"gcode_start_byte\": 34145,\n" +
                        "            \"gcode_end_byte\": 36774473,\n" +
                        "            \"layer_count\": 30,\n" +
                        "            \"object_height\": 6,\n" +
                        "            \"estimated_time\": 27609,\n" +
                        "            \"nozzle_diameter\": 0.4,\n" +
                        "            \"layer_height\": 0.2,\n" +
                        "            \"first_layer_height\": 0.2,\n" +
                        "            \"first_layer_extr_temp\": 210,\n" +
                        "            \"first_layer_bed_temp\": 60,\n" +
                        "            \"chamber_temp\": 0,\n" +
                        "            \"filament_name\": \"My Generic PLA - 标准\\\";\\\"My Generic PLA - 标准\",\n" +
                        "            \"filament_type\": \"PLA;PLA\",\n" +
                        "            \"filament_total\": 59508.8,\n" +
                        "            \"filament_weight_total\": 177.49,\n" +
                        "            \"thumbnails\": [\n" +
                        "              {\n" +
                        "                \"width\": 32,\n" +
                        "                \"height\": 32,\n" +
                        "                \"size\": 1425,\n" +
                        "                \"relative_path\": \".thumbs/冰沙机15-7H-180g-32x32.png\"\n" +
                        "              },\n" +
                        "              {\n" +
                        "                \"width\": 48,\n" +
                        "                \"height\": 48,\n" +
                        "                \"size\": 1678,\n" +
                        "                \"relative_path\": \".thumbs/冰沙机15-7H-180g-48x48.png\"\n" +
                        "              },\n" +
                        "              {\n" +
                        "                \"width\": 300,\n" +
                        "                \"height\": 300,\n" +
                        "                \"size\": 22344,\n" +
                        "                \"relative_path\": \".thumbs/冰沙机15-7H-180g-300x300.png\"\n" +
                        "              }\n" +
                        "            ]\n" +
                        "          },\n" +
                        "          \"print_duration\": 0,\n" +
                        "          \"status\": \"in_progress\",\n" +
                        "          \"start_time\": 1741846278.7388382,\n" +
                        "          \"total_duration\": 0.16346341697499156,\n" +
                        "          \"auxiliary_data\": [],\n" +
                        "          \"user\": \"_TRUSTED_USER_\",\n" +
                        "          \"exists\": true,\n" +
                        "          \"job_id\": \"000032\"\n" +
                        "        }\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  }";

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedDate = sdf.format(new Date());
                System.out.println("发送消息" + formattedDate + ":" + responseMessage1);

                // 构建要广播的消息
                sendMessage(session, responseMessage1);
//                sendMessage(session, responseMessage2);

                // 广播消息给所有客户端
//                broadcast(responseMessage1);
//                broadcast(responseMessage2);
            }
        }, 0, 1000); // 延迟0ms，间隔1000ms（1秒）
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = currentDateTime.format(formatter);
        System.out.println("收到客户端发来的消息" + formattedDateTime + ":" + message);

        // 处理业务逻辑后回复
//        sendMessage(session, "{\n" +
//                "  \"state\": \"已收到\",\n" +
//                "  \"message\":\"" + message + "\",\n" +
//                "  \"time\":\"" + formattedDateTime + "\"\n" +
//                "}");

        // 构建要广播的消息
//        String responseMessage = "{\n" +
//                "  \"state\": \"已收到\",\n" +
//                "  \"message\":\"" + message + "\",\n" +
//                "  \"time\":\"" + formattedDateTime + "\"\n" +
//                "}";
//        // 广播消息给所有客户端
//        broadcast(responseMessage);
    }

    @OnClose
    public void onClose(Session session) {
        sessionMap.remove(session.getId());
        System.out.println("连接关闭：" + session.getId());
    }

    // 向指定客户端发送消息
    public static void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 群发消息
    public static void broadcast(String message) {
        sessionMap.values().forEach(session -> sendMessage(session, message));
    }
}
